/* Copyright (c) 2012 William Steven Knauer
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
 * and associated documentation files (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge, publish, distribute,
 * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or
 * substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
 * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package com.williamknauer.android.yagol;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.ViewGroup.LayoutParams;
import android.widget.Toast;

/**
 * Main activity for the simulation.
 * 
 * @author William S Knauer <knauerw1@gmail.com>
 * @version 2012.0111
 */
public class GameActivity extends Activity {
	private static final int REQUEST_DIMENSIONS = 0;

	GameModel mGameModel;
	GameDelegate mGameDelegate;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		/*
		 * Reload previous state from Bundle.
		 */
		if (savedInstanceState != null) {
			if (savedInstanceState.containsKey("game_model")) {
				GameModel gm = savedInstanceState.getParcelable("game_model");
				GameDelegate gd = new GameDelegate(getBaseContext(), gm);
				setContentView(gd, new LayoutParams(LayoutParams.MATCH_PARENT,
						LayoutParams.MATCH_PARENT));
				mGameDelegate = gd;
				mGameModel = gm;
			} else {
				// do nothing wait for dimensions picker to launch
			}
		} else {
			/*
			 * Display splash screen for a few seconds.
			 */
			setContentView(R.layout.splash);
			new Thread() {
				@Override
				public void run() {
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					launchDimensionsPicker();
				}
			}.start();
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		/*
		 * Only write the GameModel if it has been created.
		 */
		if (mGameModel != null)
			outState.putParcelable("game_model", mGameModel);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		/*
		 * Suppress menu key presses during splash screen.
		 */
		if (keyCode == KeyEvent.KEYCODE_MENU && mGameModel == null)
			return true;
		return super.onKeyDown(keyCode, event);
	}

	private void launchDimensionsPicker() {
		Intent i = new Intent(this, DimensionsPickerActivity.class);
		startActivityForResult(i, REQUEST_DIMENSIONS);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_DIMENSIONS:
			if (resultCode == RESULT_OK) {
				/*
				 * Set up a new game with the specified dimensions.
				 */
				int rows = data.getIntExtra(
						"com.williamknauer.android.yagol.DimensionsPickerActivity.rows", 200);
				int cols = data.getIntExtra(
						"com.williamknauer.android.yagol.DimensionsPickerActivity.cols", 200);
				GameModel gm = new GameModel(rows, cols);
				GameDelegate gd = new GameDelegate(getBaseContext(), gm);
				setContentView(gd, new LayoutParams(LayoutParams.MATCH_PARENT,
						LayoutParams.MATCH_PARENT));
				mGameDelegate = gd;
				mGameModel = gm;
				Toast.makeText(this, getResources().getString(R.string.game_instructions),
						Toast.LENGTH_LONG).show();
			} else {
				/*
				 * Do nothing if dialog was canceled.
				 */
				if (mGameModel == null) {
					/*
					 * Game cannot be created. Either re-launch dimensions
					 * picker or close the whole game. Closing the game is less
					 * annoying to a naive user.
					 */
					finish();
				}
			}
			break;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.game_options_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_gameao_preferences:
			/*
			 * Launch preferences activity if menu item is selected.
			 */
			Intent i = new Intent(this, GamePreferencesActivity.class);
			startActivity(i);
			return true;
		}
		/*
		 * Pass all other item selections to GameDelegate.
		 */
		return mGameDelegate.onOptionsItemSelected(item.getItemId());
	}

	@Override
	public void onBackPressed() {
		/*
		 * Override back button with undo.
		 */
		mGameDelegate.onOptionsItemSelected(R.id.menu_gameao_reset);
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (mGameDelegate != null) {
			mGameDelegate.onPause();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (mGameDelegate != null) {
			mGameDelegate.onResume();
		}
	}

}